import { defineStore } from 'pinia'
import { onMounted, ref, watch } from 'vue'
import { usePreferredDark } from '@vueuse/core'
import { getStorage, setStorage } from '@/utils/storage'

const useSystemStore = defineStore(
  'system',
  () => {
    // 侧边栏折叠
    const fold = ref(false)
    const onFold = () => {
      fold.value = !fold.value
      const root = document.documentElement
      root.style.setProperty('--sider-width', fold.value ? '48px' : '200px')
    }

    // 黑白主题
    const isDark = usePreferredDark()
    const persistTheme = getStorage('theme')
    const theme = ref<ThemeType>(persistTheme ? persistTheme : isDark.value ? 'dark' : 'light')
    onMounted(() => {
      document.documentElement.className = theme.value
    })

    const onChangeTheme = () => {
      theme.value = theme.value === 'dark' ? 'light' : 'dark'
      document.documentElement.className = theme.value
      setStorage('theme', theme.value)
    }

    const redirectUrl = ref('') // 登录成功后跳转的地址

    watch(isDark, (nv) => {
      theme.value = nv ? 'dark' : 'light'
      document.documentElement.className = theme.value
      setStorage('theme', theme.value)
    })

    return {
      isDark,
      theme,
      onChangeTheme,
      fold,
      onFold,
      redirectUrl
    }
  },
  {
    persist: {
      storage: sessionStorage,
      paths: ['redirectUrl']
    }
  }
)

export default useSystemStore
